package com.Portal.service.impl;

import com.Portal.pojo.GoodVo;
import com.Portal.service.SearchService;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@Service
public class SearchServiceImpl implements SearchService {

    /**
     * 前台->搜索服务
     * @param keywords
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public List<GoodVo> GoodsList(String keywords, Integer pageNum, Integer pageSize) throws IOException {
        SearchRequest searchRequest=new SearchRequest();
        //指定索引库
        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
        //建查询对象
        searchSourceBuilder.from((pageNum-1)*pageSize).size(pageSize);
        //设置分页条件按
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        //设置高亮对象
        highlightBuilder.field("goodsName").preTags("<span style='color:red'>").postTags("</span>");
        //设置高亮字段及高亮样式
        searchSourceBuilder.highlighter(highlightBuilder);
        //添加查询条件
        searchSourceBuilder.query(QueryBuilders.multiMatchQuery(keywords,"goodsName"));
        searchRequest.source(searchSourceBuilder);
        //执行请求
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //处理数据
        List<GoodVo>goodVoList=new ArrayList<>();
        long totalHits = response.getHits().getTotalHits().value;
        if (totalHits<0)
            return null;


        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            Integer goodsId = Integer.valueOf((Integer) hit.getSourceAsMap().get("goodsId"));
            String goodsName = String.valueOf(hit.getSourceAsMap().get("goodsName"));
            String highlight = String.valueOf(hit.getHighlightFields().get("goodsName").fragments()[0]);
            BigDecimal marketPrice = new BigDecimal(String.valueOf(hit.getSourceAsMap().get("marketPrice")));
            String originalImg = String.valueOf(hit.getSourceAsMap().get("originalImg"));
            GoodVo goodVo = new GoodVo(goodsId, goodsName, highlight, marketPrice, originalImg);
            goodVoList.add(goodVo);
        }
        return goodVoList;
    }
}
